using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimplePoker.Main
{
    public class SimpleGeneticSimulation
    {
        public static void Start()
        {
            var players = new List<SimpleGeneticPlayer>();

            for (int i = 0; i < 60; i++)
            {
                Console.WriteLine("Initialising player...");
                for (int x = 0; x < 10000000; x++)
                {
                    //more randomness   
                }
                players.Add(new SimpleGeneticPlayer("Genetic"));
            }



            for (int i = 0; i < 25000; i++)
            {
                Console.Clear();
                Console.WriteLine("Simulation : " + i);

                foreach (var p in players)
                {
                    PrintPlayer(p);
                }

                for (int j = 0; j < 10; j += 2)
                {
                    DoSimulation(players[j], players[j + 1]);
                }

                var lowest = players.First(p => p.FitnessRating == players.Min(x => x.FitnessRating));
                players.Remove(lowest);
                var highest = players.First(p => p.FitnessRating == players.Max(x => x.FitnessRating));
                players.Remove(highest);
                var secondHighest = players.First(p => p.FitnessRating == players.Max(x => x.FitnessRating));

                var newbie = highest.Mate(secondHighest);

                players.Add(highest);
                players.Add(newbie);
                players = players.OrderBy(x => x.FitnessRating).ToList();
            }



        }

        private static void PrintPlayer(SimpleGeneticPlayer p1)
        {
            string format = "Generation {0}\t, DNA: {1}";
            Console.WriteLine(string.Format(format, p1.Generation, p1.GetDNA()));
        }

        private static void DoSimulation(SimpleGeneticPlayer p1, SimpleGeneticPlayer p2)
        {
            p1.FitnessRating = 0;
            p2.FitnessRating = 0;

            for (int i = 0; i < 9; i++)
            {
                p1.ChipCount = 1000;
                p2.ChipCount = 1000;

                Tournament t = new Tournament(p1, p2);

                if (t.GetWinner() == p1)
                {
                    p1.FitnessRating++;
                    p2.FitnessRating--;
                }
                else
                {
                    p2.FitnessRating++;
                    p1.FitnessRating--;
                }

            }
        }
    }
}
